package coordinator

import (
	"adai.design/homemaster/container/accessory"
	"encoding/binary"
	"adai.design/homemaster/log"
	"fmt"
	"time"
)

type zigbeeMotionSensor struct {
	*ZigbeeDescriptor
	acc *accessory.MotionSensor
	time *time.Timer
}

func (z *zigbeeMotionSensor) update(data []byte) error {
	//srcAddr := binary.BigEndian.Uint16(data[1:])
	//endpoint := data[3]
	clusterId := data[4:6]
	//attributeId := data[6:8]
	//dataType := data[8]
	//value := data[9:]
	target := data[11:]

	//log.Info("attribute: netaddr(%04x) endpoint(%d) clusterId(%x) attributeId(%x) dataType(%x) value(%x) target(%x)",
	//	srcAddr, endpoint, clusterId, attributeId, dataType, value, target)

	switch fmt.Sprintf("%x", clusterId) {
	case "0406":	// 人体感应
		log.Info("motion on")
		if z.time != nil {
			z.time.Reset(time.Second * 130)
		} else {
			z.acc.Motion.OnOff.UpdateValue(true)
			z.time = time.AfterFunc(time.Second * 130, func() {
				z.time.Stop()
				z.time = nil
				log.Info("motion off")
				z.acc.Motion.OnOff.UpdateValue(false)
			})
		}

	case "0400": 	// 光照强度
		lux := binary.BigEndian.Uint16(target)
		log.Info("lux: %d", lux)
		z.acc.Motion.Lightness.UpdateValue(lux)
	}
	return nil
}

func newMotionSensor(zigbee *ZigbeeDescriptor) *zigbeeMotionSensor {
	sensor := &zigbeeMotionSensor{
		ZigbeeDescriptor: zigbee,
		acc: accessory.NewMotionSensor(zigbee.MacAddr),
	}
	return sensor
}

const xiaoMiMotionSensorEndpointDefault =
	`[
         {
             "endpoint": 1,
             "profile_id": "0104",
             "device_id": "0107",
             "input_cluster": [
                 "0000",
                 "ffff",
                 "0406",
                 "0400",
                 "0500",
                 "0001",
                 "0003"
             ],
             "output_cluster": [
                 "0000",
                 "ffff"
             ]
         },
		 "manufacturer": "LUMI",
		 "mode": "lumi.sensor_motion.aq2",
       	 "date": "20160516"
	]`